<template>
	<div class="data-statistics">
		<div class="data-statistics-box">
			<header class="title">
				数据统计
				<div style="float: right; display: flex">
					<div class="day-list">
						<p
							:key="item.value"
							v-for="item in dateRangeList"
							:class="item.value == personActive ? 'active' : ''"
							@click="personChange(item.value)"
						>
							{{ item.name }}<span></span>
						</p>
					</div>
					<a-range-picker
						v-if="personActive === 5"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						:value="[startTime, endTime]"
						:placeholder="['开始时间', '结束时间']"
						input-read-only
						class="date"
						@calendar-change="changeRangePicker"
					>
						<template #suffixIcon>
							<clock-circle-outlined></clock-circle-outlined>
						</template>
					</a-range-picker>
				</div>
			</header>
			<main class="data-statistics-main">
				<div class="data-statistics-main-left">
					<data-statistics-card title="人员统计" class="main-left-card">
						<template #header-left>
							<global-svg-icon
								icon-name="data-download"
								style="cursor: pointer"
								width="18"
								height="20"
								@click="exportPerson"
							></global-svg-icon>
						</template>
						<template #Content>
							<div class="workshop-container">
								<div :key="item.groupId" v-for="item in workshopList" @click="showTable(item)">
									<div class="workshop-title">{{ item.groupName }}</div>
									<div class="workshop-num">
										<p>{{ item.count }}</p>
									</div>
								</div>
							</div>
						</template>
					</data-statistics-card>

					<data-statistics-card title="算法报警次数统计" class="main-left-card main-left-card-bottom">
						<template #header-left>
							<global-svg-icon
								icon-name="data-download"
								style="cursor: pointer"
								width="18"
								height="20"
								@click="exportAlarm('alarm')"
							></global-svg-icon>
						</template>

						<template #Content>
							<div class="algorithm-police">
								<div
									style="display: grid; grid-template-columns: 2fr 1fr 1fr; grid-column-gap: 6px; align-items: center; padding: 2px 24px"
								>
									<span>算法名称</span>
									<span style="text-align: right">报警次数</span>
									<span>占比</span>
								</div>

								<div style="height: calc(100% - 50px - 22px)">
									<vue-scroll>
										<div :key="item.aiSrvId" v-for="item in algorithmAlarmList" class="algorithmAlarmList-item">
											<span>{{ item.aiSrvName }}</span>
											<span style="text-align: right">{{ item.alarmCount }}</span>
											<span>{{ item.rate }}</span>
										</div>
									</vue-scroll>
								</div>
							</div>
						</template>
					</data-statistics-card>
				</div>

				<div class="data-statistics-main-right">
					<data-statistics-card title="人员违章次数统计" :show-control="true" class="main-right-card">
						<template #header-left>
							<global-svg-icon
								icon-name="data-download"
								style="cursor: pointer"
								width="18"
								height="20"
								@click="exportAlarm('person')"
							></global-svg-icon>
						</template>

						<template #Content>
							<div ref="echartDom" :style="{ width: '1144px', height: '282px' }"></div>
						</template>
					</data-statistics-card>

					<data-statistics-card title="单位违章次数统计" :show-control="true" class="main-right-card">
						<template #header-left>
							<global-svg-icon
								icon-name="data-download"
								style="cursor: pointer"
								width="18"
								height="20"
								@click="exportAlarm('unit')"
							></global-svg-icon>
						</template>
						<template #header-right>
							<a-select :value="searchState.selectValue" style="width: 120px" @change="ChangeSelect">
								<a-select-option :key="item.groupId" v-for="item in workList" :value="item.groupId">{{ item.groupName }}</a-select-option>
							</a-select>
						</template>
						<template #Content>
							<div ref="echartUnitDom" :style="{ width: '1144px', height: '282px' }"></div>
						</template>
					</data-statistics-card>
				</div>
			</main>
		</div>
		<a-modal v-model:open="show" :centered="true" width="750px" :footer="false" :title="`${detail.groupName}（${detail.count}人）`">
			<div class="card-item">
				<div class="punish-list">
					<div class="punish-list-header">
						<p class="item">班组名称</p>
						<p class="item">人数/人</p>
					</div>

					<div style="height: calc(304px - 38px)">
						<vue-scroll>
							<div :key="item.groupId" v-for="item in dataSource" class="punish-list-item">
								<div class="item">{{ item.groupName }}</div>
								<div class="item">{{ item.count }}</div>
							</div>
						</vue-scroll>
					</div>
				</div>
			</div>
		</a-modal>
	</div>
</template>

<script setup lang="ts">
import { dataStatisticsApi } from '../../api';
import * as echarts from 'echarts';
import httpServe from '@/global-services';
import { DataStatisticsCard } from '../../components';
const dateRangeList = [
	{ value: 4, name: '今日' },
	{ value: 0, name: '本周' },
	{ value: 1, name: '本月' },
	{ value: 2, name: '本季度' },
	{ value: 3, name: '本年' },
	{ value: 5, name: '自定义' }
];
const exportFile = (data: any) => {
	const href = window.URL.createObjectURL(new Blob([data?.data]));
	const a = document.createElement('a');
	a.href = href || '';
	// eslint-disable-next-line quotes
	const fileName = data?.title.split('utf-8' + "''")[1];
	a.download = decodeURIComponent(fileName);
	a.click();
	a.remove();
};
/* ------------------- 车间列表 ------------------ */
const workshopList = ref([
	{
		count: 0,
		groupName: '',
		groupId: ''
	}
]);
const workList = ref([{ groupName: '全部车间', groupId: '' }]);
const getPersonList = async (): Promise<void> => {
	try {
		let res: any = await dataStatisticsApi.getPersonCount();
		if (res.code === 0) {
			workshopList.value = res.data.personCountList;
			workList.value = workList.value.concat(res.data.personCountList);
		}
	} catch (error) {
		console.log(error);
	}
};
const dataSource = ref([
	{
		count: 0,
		groupName: '',
		groupId: ''
	}
]);
/** 人员导出数据 */
const exportPerson = async () => {
	let res = await httpServe.postHttp('/base/dataStatistics/exportPersonCount')('', { responseType: 'blob' });
	exportFile(res);
};

const detail = ref({ count: 0, groupName: '', groupId: '' });
const personActive = ref(4);
const show = ref(false);
const searchState = ref({
	selectValue: ''
});

const showTable = async (data: any) => {
	show.value = true;
	detail.value = data;
	try {
		let res: any = await dataStatisticsApi.getQueryBanzuCount({ chejianId: data.groupId });
		if (res.code === 0) {
			dataSource.value = res.data.banzuPersonCountList;
		}
	} catch (error) {
		console.log(error);
	}
};
// 人员柱状图

// There should not be negative values in rawData
const rawData = ref<any>([[]]);

const personList = ref([]);

const echartDom = ref(); // 使用ref创建虚拟DOM引用，使用时用main.value
const echartUnitDom = ref('');

const getPersonEchart = (series: any) => {
	let myChart = echarts.init(echartDom.value);

	let option = {
		tooltip: {
			trigger: 'axis',
			backgroundColor: 'rgba(21, 23, 27, 0.95)',
			borderColor: 'rgba(21, 23, 27, 0.95)',
			color: 'rgba(255, 255, 255, 0.52)',
			formatter: function (params: any) {
				// params 是一个数组，数组中包含每个系列的数据信息
				let result = '';
				let results = '';
				let total = 0;
				params.forEach((item: any) => {
					// item 是每一个系列的数据
					const seriesName = item.seriesName; // 系列名称
					const value = item.value; // 数据值
					total += value;
					result += `${seriesName} <span style="float:right;margin-left:15px;">${value}</span><br/>`;
				});
				results += `<p>违章总数<span style="float:right">${total}</span></p> <hr style="border-color:#FFFFFF1A">`;

				return results + result;
			},
			axisPointer: {
				// Use axis to trigger tooltip
				type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
			}
		},
		xAxis: {
			data: [...personList.value],
			axisTick: {
				show: false
			},
			axisLabel: {
				normal: {
					textStyle: {
						color: 'rgba(255, 255, 255, 0.6)'
					}
				},
				// 默认x轴字体大小
				fontSize: 12,
				// margin:文字到x轴的距离
				margin: 6,
				height: 17,
				color: 'rgba(255, 255, 255, 0.6)'
			},
			axisLine: {
				show: true,
				lineStyle: {
					color: 'rgba(255, 255, 255, 0.1)'
				}
			}
		},
		yAxis: {
			type: 'value',
			name: '单位（次）',
			splitLine: {
				show: true,
				lineStyle: { color: 'rgba(255, 255, 255, 0.1)' }
			}
		},
		grid: { top: 50, left: 40, right: 40, bottom: 20 },
		series
	};
	myChart.setOption(option);
};

const getPersonAlarmList = async (): Promise<void> => {
	let myChart = echarts.init(echartDom.value);
	myChart.dispose();

	try {
		let params = {
			timeInterval: personActive.value,
			startTime: startTime.value,
			endTime: endTime.value
		};
		let res: any = await dataStatisticsApi.getPersonViolateRegCount(params);
		personList.value = [];
		if (res.code === 0) {
			if (res.data) {
				personList.value = res.data.everyPersonViolateInfo.map((p: any) => p.personName);
				let violateList = res.data.everyPersonViolateInfo[0].everyAiViolateCountList.map((p: any) => p.aiSrvName);
				violateList.forEach((ele: any, i: number) => {
					rawData.value[i] = res.data.everyPersonViolateInfo.map((p: any) => p.everyAiViolateCountList[i].violateCount);
				});
				const series: any[] = violateList.map((name: any, sid: any) => {
					return {
						name,
						type: 'bar',
						stack: 'total',
						barWidth: '60%',
						itemStyle: {
							color: `rgba(61, 127, 233, ${1 / (sid + 1)})`
						},
						data: rawData.value[sid]
					};
				});
				getPersonEchart(series);
			} else {
				// let violateList: any[] = [];
				// violateList.forEach((ele: any, i: number) => {
				// 	rawData.value[i] = res.data.everyPersonViolateInfo.map((p: any) => p.everyAiViolateCountList[i].violateCount);
				// });
				// const series: any[] = violateList.map((name: any, sid: any) => {
				// 	return {
				// 		name,
				// 		type: 'bar',
				// 		stack: 'total',
				// 		barWidth: '60%',
				// 		itemStyle: {
				// 			color: `rgba(61, 127, 233, ${1 / (sid + 1)})`
				// 		},
				// 		data: rawData.value[sid]
				// 	};
				// });
				getPersonEchart([]);
			}
		}
	} catch (error) {
		console.log(error);
	}
};
/* ------------ 单位违章次数统计 -----------*/
const unitList = ref([{ chejianName: '', banzuName: '', count: '' }]);
const getUnitList = async (): Promise<void> => {
	try {
		let params = {
			groupId: searchState.value.selectValue,
			timeInterval: personActive.value,
			startTime: startTime.value,
			endTime: endTime.value
		};
		let res: any = await dataStatisticsApi.getUnitCount(params);
		if (res.code === 0) {
			if (res.data) {
				unitList.value = res.data.perChejianViolateList;
			} else {
				unitList.value = [];
			}
			getUnitEchart();
		}
	} catch (error) {
		console.log(error);
	}
};
const getUnitEchart = async (): Promise<void> => {
	let myChart = echarts.init(echartUnitDom.value);
	let option = {
		tooltip: {
			trigger: 'axis',
			show: false,
			axisPointer: {
				// Use axis to trigger tooltip
				type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
			}
		},
		xAxis: {
			type: 'category',
			data: unitList.value.map((p) => p.banzuName),
			axisTick: {
				show: false
			},
			axisLabel: {
				normal: {
					textStyle: {
						color: 'rgba(255, 255, 255, 0.6)'
					}
				},
				// 默认x轴字体大小
				fontSize: 12,
				// margin:文字到x轴的距离
				margin: 6,
				height: 17,
				color: 'rgba(255, 255, 255, 0.6)',
				formatter: function (value: any, index: any) {
					return `${unitList.value[index].chejianName}\n` + value;
				}
			},
			axisLine: {
				show: true,
				lineStyle: {
					color: 'rgba(255, 255, 255, 0.1)'
				}
			}
		},
		yAxis: {
			type: 'value',
			name: '单位（次）',
			splitLine: {
				show: true,
				lineStyle: {
					color: 'rgba(255, 255, 255, 0.1)'
				}
			}
		},
		grid: {
			top: 40,
			left: 70,
			right: 40,
			bottom: 40
		},
		series: [
			{
				data: unitList.value.map((p) => p.count),
				type: 'bar',
				itemStyle: {
					// 设置柱状图的颜色
					color: '#45BBD3'
				}
			}
		]
	};
	// 使用刚指定的配置项和数据显示图表。
	myChart.setOption(option);
};

/* ------------ 算法报警次数统计 -----------*/
const algorithmAlarmList = ref([
	// {
	// 	aiSrvId: 0,
	// 	aiSrvName: '',
	// 	alarmCount: 0,
	// 	rate: 0
	// }
]);
/** 报警导出数据 */
const exportAlarm = async (type: string) => {
	let params: any = {
		timeInterval: personActive.value,
		startTime: startTime.value,
		endTime: endTime.value
	};
	let res: any = '';
	if (type === 'alarm') {
		res = await httpServe.postHttp('/base/dataStatistics/exportAlgorithmAlarmCount')(params, { responseType: 'blob' });
	}
	if (type === 'person') {
		res = await httpServe.postHttp('/base/dataStatistics/exportPersonViolateCount')(params, { responseType: 'blob' });
	}
	if (type === 'unit') {
		params['groupId'] = searchState.value.selectValue;
		res = await httpServe.postHttp('/base/dataStatistics/exportChejianViolateCount')(params, { responseType: 'blob' });
	}
	exportFile(res);
};
// 时间过滤
const startTime = ref<any>();
const endTime = ref<any>();
//算法报警
const getAlgorithmAlarmCount = async (): Promise<void> => {
	try {
		let params = {
			timeInterval: personActive.value,
			startTime: startTime.value,
			endTime: endTime.value
		};
		let res: any = await dataStatisticsApi.getAlgorithmAlarmCount(params);
		if (res.code === 0) {
			algorithmAlarmList.value = res.data;
		}
	} catch (error) {
		console.log(error);
	}
};
const changeRangePicker = (dates: any): void => {
	startTime.value = dates[0];
	endTime.value = dates[1];
	getAlgorithmAlarmCount();
	getUnitList();
};
const personChange = (e: number) => {
	personActive.value = e;
	if (e !== 5) {
		getUnitList();
		getAlgorithmAlarmCount();
		getPersonAlarmList();
	}
};
const ChangeSelect = (e: string) => {
	searchState.value.selectValue = e;
	getUnitList();
};
onMounted(() => {
	getUnitList();
	getPersonList();
	getPersonAlarmList();
	getAlgorithmAlarmCount();
});
</script>

<style lang="less" scoped>
.card-item {
	border-radius: 4px;
	padding: 20px 20px 40px;
	box-shadow: 0 40px 180px 0 rgba(0, 0, 0, 0.35);
}

.punish-item-header {
	display: flex;
	height: 30px;
	font-size: 14px;
	font-weight: 400;
	font-style: normal;
	line-height: 22px;
	color: #b0b5c0;
	align-items: center;
	justify-content: space-between;
}

.punish-list {
	margin-top: 10px;
	border: 1px solid #2b3a50;
	border-radius: 6px;

	.punish-list-header {
		display: flex;
		height: 38px;
		border-bottom: 1px solid #2b3a50;
		font-size: 14px;
		font-weight: 700;
		line-height: 22px;
		color: #8b949e;
		align-items: center;

		.item {
			width: 200px;
			padding: 2px 16px;
			line-height: 30px;
		}
	}

	.punish-list-item {
		display: flex;
		align-items: center;
		height: 38px;
		border-bottom: 1px solid #2b3a50;
		font-size: 14px;
		font-weight: 400;
		line-height: 22px;
		color: #f0f6fc;

		.item {
			width: 200px;
			padding: 2px 16px;
			line-height: 30px;
		}
	}
}

.data-statistics {
	--header-h: 48px;

	width: 100%;
	min-width: auto !important;
	height: 100%;
	padding: 24px 16px;

	.title {
		height: var(--header-h);
		font-family: 'Noto Sans SC';
		font-size: 20px;
		font-weight: 700;
		font-style: normal;
		color: rgba(240, 246, 252, 0.95);
	}

	.day-list {
		display: flex;
		min-width: 280px;
		margin: 0 8px;
		border: 1px solid #f0f6fc1a;
		border-radius: 6px;
		padding: 3px;
		cursor: pointer;
		justify-content: space-between;

		p {
			position: relative;
			min-width: 49.4px;
			height: 30px;
			margin: 0 3px 0 0;
			border-radius: 4px;
			padding: 0 2px;
			font-size: 14px;
			line-height: 30px;
			text-align: center;
			color: #b0b5c0;

			span {
				position: absolute;
				top: 5px;
				right: -3px;
				width: 1px;
				height: 20px;
				background: #e8e8eb;
				opacity: 0.2;
			}
		}

		.active {
			font-weight: 700;
			color: #f0f6fc;
			background: #305dc2;
		}

		p:last-child {
			span {
				display: none;
			}
		}
	}

	.data-statistics-box {
		width: 100%;
		height: 100%;
		border: 1px solid @borderColor01;
		border-radius: 8px;
		padding: 24px 32px 32px;
		background: rgba(8, 22, 59, 0.4);
		backdrop-filter: blur(2px);

		.data-statistics-main {
			display: flex;
			width: 100%;
			height: calc(100% - var(--header-h));
			align-items: center;
			gap: 0 16px;

			.data-statistics-main-left,
			.data-statistics-main-right {
				display: flex;
				height: 100%;
				gap: 16px 0;
				align-items: center;
				flex-direction: column;
			}

			.data-statistics-main-left {
				width: 465px;

				.main-left-card:first-child {
					height: 176px;
				}

				.main-left-card-bottom {
					height: calc(100% - 176px);
				}

				.workshop-container {
					display: flex;
					justify-content: space-between;
					margin-top: 20px;

					> div {
						width: 33.33%;
						text-align: center;
						cursor: pointer;

						.workshop-title {
							font-size: 14px;
							line-height: 26px;
							color: #fff;
							background: url('../../../../global-assets/imgs/workshop_title.png') no-repeat top left;
							background-size: 100% 100%;
						}

						.workshop-num {
							height: 80px;
							background: url('../../../../global-assets/imgs/workshop_num.png') no-repeat bottom center;
							background-size: 101px auto;

							p {
								padding-top: 13px;
								font-size: 24px;
								font-weight: 700;
								line-height: 34.75px;
								text-align: center;
								color: #fff;
							}
						}
					}
				}

				.algorithm-police {
					height: 100%;
					padding-top: 20px;

					div {
						width: 100%;
						font-size: 14px;
						line-height: 46px;
						text-align: left;
						color: #fffc;

						span {
							display: inline-block;
						}

						span:first-child {
							width: 220px;
						}

						span:nth-child(2n) {
							box-sizing: border-box;
							width: 69px;
							padding-right: 13px;
							text-align: right;
						}

						span:last-child {
							width: 52px;
							text-align: right;
						}
					}

					div:first-child {
						color: #8b949e;

						span:nth-child(2n) {
							padding-right: 0;
							text-align: left;
						}
					}

					.algorithmAlarmList-item {
						display: grid;
						grid-template-columns: 2fr 1fr 1fr;
						grid-column-gap: 6px;
						align-items: center;
						padding: 2px 24px;

						&:nth-child(2n) {
							background-color: rgba(148, 191, 255, 0.1);
						}
					}
				}
			}

			.data-statistics-main-right {
				flex: 1;

				.main-right-card {
					flex: 1;

					.date {
						width: 216px;
					}
				}
			}
		}
	}
}
</style>
